﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Hydra.Shell.Interfaces;
using SLControlLibrary;

namespace Hydra.Shell.Implementations
{
    public class HandlerExceptionEventArgs : EventArgs
    {
        public Exception Exception { get; set; }

        public HandlerExceptionEventArgs()
        {
        }

        public HandlerExceptionEventArgs(Exception ex)
        {
            this.Exception = ex;
        }
    }

    public class HandlerLoadEventArgs : EventArgs
    {
        public IUnknown Handler { get; set; }

        public HandlerLoadEventArgs()
        {
        }

        public HandlerLoadEventArgs(IUnknown Handler)
        {
            this.Handler = Handler;
        }
    }

    public delegate void HandlerLoadHandler(object sender, HandlerLoadEventArgs e);
    public delegate void HandlerExceptionHandler(object sender, HandlerExceptionEventArgs e);

    public class HandlerLoadOperation
    {
        public event HandlerLoadHandler HandlerLoaded;
        public event HandlerExceptionHandler ExceptionOccured;
        public IUnknown Handler { get; set; }
        public bool HandlerAvailable { get; set; }
        public Exception Exception { get; set; }
        private UIThread uiThread;

        public HandlerLoadOperation(UIThread uiThread)
        {
            this.uiThread = uiThread;
        }

        public HandlerLoadOperation(Exception ex, UIThread uiThread)
        {
            this.Exception = ex;
            this.uiThread = uiThread;
        }

        public bool HasException
        {
            get
            {
                return this.Exception != null;
            }
        }

        public void SetLoaded(IUnknown Handler)
        {
            this.Handler = Handler;
            this.HandlerAvailable = true;

            HandlerLoaded(this, new HandlerLoadEventArgs(Handler));
        }

        public void SetException(Exception ex)
        {
            ExceptionOccured(this, new HandlerExceptionEventArgs(ex));
        }

        public void DelaySetLoaded(IUnknown package)
        {
            this.Handler = package;
            this.HandlerAvailable = true;

            uiThread.Run(() =>
            {
                HandlerLoaded(this, new HandlerLoadEventArgs(package));
            });
        }

        public void DelaySetException(Exception ex)
        {
            this.Exception = ex;

            uiThread.Run(() =>
            {
                ExceptionOccured(this, new HandlerExceptionEventArgs(ex));
            });
        }
    }
}
